import json
import logging
import re
from django.conf import settings
from django.contrib.auth import login, authenticate, logout
from django.core.mail import send_mail
from django.http import HttpResponseForbidden, HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django_redis import get_redis_connection
from pymysql import DatabaseError

from carts.utils import merge_cart_cookies_to_redis
from celery_tasks.email.tasks import send_verify_email
from goods.models import SKU
from . import constants
from .models import User, Address
from meiduo_mall.utils.response_code import RETCODE
from .utils import LoginRequireMixin, generate_verify_email_url, check_verify_email_token, LoginRequiredJSONMixin

logger = logging.getLogger('django')




class UserPassword(LoginRequiredJSONMixin,View):
    def get(self,request):
        # 提供修改密码页面
        return render(request, 'user_center_pass.html')

    def put(self,request):
        # 修改密码
        json_dict = json.loads(request.body.decode())
        old_password = json_dict.get('old_password')
        new_password = json_dict.get('new_password')
        new_password2 = json_dict.get('new_password2')
        if not all([old_password,new_password,new_password2]):
            return JsonResponse({'code':RETCODE.PWDERR,'errmsg':'缺少必要参数'})
        # 校验密码
        if new_password != new_password2:
            return JsonResponse({'code': RETCODE.PWDERR, 'errmsg': '两次输入密码不一致'})
        if not request.user.check_password(old_password):
            return JsonResponse({'code':RETCODE.PWDERR,'errmsg':'原密码错误'})
        #修改密码
        request.user.set_password(new_password)
        request.user.save()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '密码修改成功'})


class UserBrowerHistroy(LoginRequiredJSONMixin,View):
    """用户浏览记录"""
    def get(self,request):
        """获取用户浏览记录"""
        redis_conn = get_redis_connection('history')
        sku_ids = redis_conn.lrange('history_%s' % request.user.id,0,-1)
        # 根据sku_id查询出商品信息
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append({
                'id':sku.id,
                'name':sku.name,
                'default_image':sku.default_image.url,
                'price':sku.price,

            })
        return JsonResponse({'code':RETCODE.OK,'errmsg':'OK','skus':skus})


    def post(self,request):
        """保存用户浏览记录"""
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')

        # 校验参数
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('sku不存在')
        # 保存用户浏览记录
        user_id = request.user.id
        redis_conn = get_redis_connection('history')
        pl = redis_conn.pipeline()
        # 去重
        pl.lrem('history_%s' % user_id,0,sku_id)
        # 插入
        pl.lpush('history_%s' % user_id,sku_id)
        # 只保留前５条,截取
        pl.ltrim('history_%s' % user_id,0,4)
        # 执行语句
        pl.execute()

        return JsonResponse({'code':RETCODE.OK,'errmsg':'OK'})

class DefaultAddressView(LoginRequiredJSONMixin, View):
    """设置默认地址"""

    def put(self, request, address_id):
        """设置默认地址逻辑"""

        try:
            address = Address.objects.get(id=address_id)
            request.user.default_address = address
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新默认地址失败'})
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '更新默认地址成功'})


class UpdateTitleAddressView(LoginRequiredJSONMixin, View):
    """设置地址标题"""

    def put(self, request, address_id):
        """设置地址标题逻辑"""

        # 　接受参数
        json_dict = json.loads(request.body.decode())
        title = json_dict['title']
        try:
            address = Address.objects.get(id=address_id)
            address.title = title
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址标题失败'})
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址标题成功'})


class UpdateDestroyAddressView(LoginRequiredJSONMixin, View):
    """修改和删除地址"""

    def put(self, request, address_id):
        """修改地址逻辑"""

        # 接受参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict['receiver']
        province_id = json_dict['province_id']
        city_id = json_dict['city_id']
        district_id = json_dict['district_id']
        place = json_dict['place']
        mobile = json_dict['mobile']
        tel = json_dict['tel']
        email = json_dict['email']
        # 校验参数
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseForbidden('缺少必要参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('手机号码错误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseForbidden('固定号码错误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseForbidden('邮箱错误')
        # 更新地址
        try:
            Address.objects.filter(id=address_id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                email=email,
            )
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新地址失败'})
        # 响应前端
        address = Address.objects.get(id=address_id)
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }

        return JsonResponse({'code': RETCODE.OK, 'errmsg': '更新地址成功', 'address': address_dict})

    def delete(self, request, address_id):
        """删除地址"""
        try:
            address = Address.objects.get(id=address_id)
            address.is_deleted = True
            address.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '删除地址失败'})
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '删除地址成功'})


class CreateAddressView(LoginRequiredJSONMixin, View):
    """新增地址"""

    def post(self, request):
        """实现新增地址逻辑"""
        # 校验地址数量上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count > constants.USER_ADDRESS_COUNT_LIMIT:
            return JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '超出用户地址上限'})
        # 　参数
        json_dict = json.loads(request.body.decode())
        receiver = json_dict['receiver']
        province_id = json_dict['province_id']
        city_id = json_dict['city_id']
        district_id = json_dict['district_id']
        place = json_dict['place']
        mobile = json_dict['mobile']
        tel = json_dict['tel']
        email = json_dict['email']

        # 　校验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return HttpResponseForbidden('缺少必要参数')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('手机号码错误')
        if tel:
            if not re.match(r'^(0[0-9]{2,3}-)?([2-9][0-9]{6,7})+(-[0-9]{1,4})?$', tel):
                return HttpResponseForbidden('固定号码错误')
        if email:
            if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
                return HttpResponseForbidden('邮箱错误')
        # 保存信息

        try:
            address = Address.objects.create(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                email=email,
            )
            if not request.user.default_address:
                request.user.default_address = address
                request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '新增地址失败'})

        # 响应前端
        address_dict = {
            'id': address.id,
            'title': address.title,
            'receiver': address.receiver,
            'province': address.province.name,
            'city': address.city.name,
            'district': address.district.name,
            'place': address.place,
            'mobile': address.mobile,
            'tel': address.tel,
            'email': address.email,
        }

        return JsonResponse({'code': RETCODE.OK, 'errmsg': '新增地址成功', 'address': address_dict})


class AddressView(LoginRequireMixin, View):
    """用户收货地址"""

    def get(self, request):
        """提供收货地址界面"""
        # 　获取用户地址列表
        user = request.user
        addresses = Address.objects.filter(user=user, is_deleted=False)
        if not addresses:
            addresses_dict_list = {}
            context = {
                'deafult_address_id': user.default_address_id,
                'addresses': addresses_dict_list
            }
            return render(request, 'user_center_site.html', context)
        addresses_dict_list = []
        for add in addresses:
            address_dict = {
                "id": add.id,
                "title": add.title,
                "receiver": add.receiver,
                "province": add.province.name,
                "city": add.city.name,
                "district": add.district.name,
                "place": add.place,
                "mobile": add.mobile,
                "tel": add.tel,
                "email": add.email
            }
            addresses_dict_list.append(address_dict)
            context = {
                'deafult_address_id': user.default_address_id,
                'addresses': addresses_dict_list
            }
        return render(request, 'user_center_site.html', context)


class EmailView(LoginRequireMixin, View):
    """添加邮箱"""

    def put(self, request):
        """实现添加邮箱的逻辑"""
        json_dict = json.loads(request.body.decode())
        email = json_dict['email']

        if not email:
            return HttpResponseForbidden('缺少ｅｍａｉｌ参数')
        if not re.match(r'^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return HttpResponseForbidden('邮箱错误')

        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '添加邮箱失败'})
        verify_url = generate_verify_email_url(request.user)
        send_verify_email.delay(email, verify_url=verify_url)
        return JsonResponse({'code': RETCODE.OK, 'errmsg': '添加邮箱成功'})


class VerifyEmailView(View):
    """验证邮箱"""

    def get(self, request):
        """实现验证邮箱逻辑"""
        token = request.GET.get('token')

        if not token:
            return HttpResponseForbidden('缺少参数ｔｏｋｅｎ')

        user = check_verify_email_token(token)
        if not user:
            return HttpResponseForbidden('无效的token')
        # 改变邮箱状态
        try:
            user.email_active = True
            user.save()
        except Exception as e:
            logger.error(e)
            return HttpResponseForbidden('激活邮件失败')
        return redirect(reverse('users:info'))


class LoginView(View):
    """用户登录"""

    def get(self, request):
        """
        提供登录界面
        :param request:请求对象
        :return: 登录界面
        """
        return render(request, 'login.html')

    def post(self, request):
        """
        实现登录
        :param request:请求对象
        :return: 登录结果
        """
        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        if not all([username, password]):
            return HttpResponseForbidden('缺少必要参数')
        if not re.match(r'^[a-zA-Z0-9-_]{5,20}$', username):
            return HttpResponseForbidden('用户名必须是５－２０位字符')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('密码必须是8-12位密码')

        user = authenticate(request,username=username, password=password)
        if not user:
            return render(request, 'login.html', {'account_errmsg': '用户名或者密码错误'})
        login(request, user)
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)
        # django提供的next参数使用
        if request.GET.get('next'):
            response = redirect(reverse('users:info'))
        else:
            response = redirect(reverse('contents:index'))
        response.set_cookie('username', username, max_age=3600 * 24 * 15)
        response = merge_cart_cookies_to_redis(request,user,response)
        return response


class LoginOutView(View):
    """用户退出"""

    def get(self, request):
        """
        实现用户退出逻辑
        :param request:请求对象
        :return: 重定向首页
        """
        logout(request)

        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')
        return response


class UserInfoView(LoginRequireMixin, View):
    """用户中心"""

    def get(self, request):
        """
        返回用户中心页面,提供个人信息
        :param request: 请求对象
        :return: 用户中心页面
        """
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context)


class RegisterView(View):
    """用户注册"""

    def get(self, request):
        """
        提供注册界面
        :param request:请求对象
        :return: 注册界面
        """
        return render(request, 'register.html')

    def post(self, request):
        """
        实现用户注册
        :param request: 请求对象
        :return: 注册结果
        """
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        allow = request.POST.get('allow')
        sms_code_client = request.POST.get('sms_code')
        # 校验
        if not all([username, password, password2, mobile, allow, sms_code_client]):
            return HttpResponseForbidden('缺少必要参数')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
            return HttpResponseForbidden('请输入8-12位密码')
        if not re.match(r'^[0-9A-Za-z]{8,20}$', password2):
            return HttpResponseForbidden('请输入8-12位密码')
        if password != password2:
            return HttpResponseForbidden('两次输入密码不一致')
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('请输入正确的手机号码')
        if allow != 'on':
            return HttpResponseForbidden('请勾选用户协议')
        redis_conn = get_redis_connection('verify_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile).decode()
        if sms_code_server is None:
            return render(request, 'register.html', {'sms_code_errmsg': '验证码已过期'})
        if sms_code_server != sms_code_client:
            return render(request, 'register.html', {'sms_code_errmsg': '验证码输入有误'})
        try:
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        except Exception as e:
            print(e)
            return render(request, 'register.html', {'register_errmsg': '注册失败'})
        login(request, user)
        response = redirect(reverse('contents:index'))
        response.set_cookie('username', username, max_age=3600 * 24 * 15)
        response = merge_cart_cookies_to_redis(request,user,response)
        return response


class UsernameCountView(View):
    """
    验证用户名是否重复
    """

    def get(self, request, username):
        """

        :param request: 请求对象
        :param username: 用户名
        :return: json
        """
        count = User.objects.filter(username=username).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """手机号码重复验证"""

    def get(self, request, mobile):
        """
        验证手机号码重复
        :param request:请求对象
        :param mobile: 手机号
        :return: json
        """
        count = User.objects.filter(mobile=mobile).count()
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})
